package controller;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import java.util.Map;
import java.util.Set;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import ecommerce.service.CategoriaService;
import ecommerce.service.ProductoService;
import ecommerce.to.CategoriaTO;
import ecommerce.to.ProductoTO;
import ecommerce.util.EcommerceLog;

public class ProductoServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void service(HttpServletRequest request, 
                        HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);

        String accion = request.getParameter("accion");
        ProductoService proSer = new ProductoService();
        
        if(accion.equals("abrir_producto_nuevo")) {            

            ArrayList<CategoriaTO> categorias = null;
            CategoriaService cateSer = new CategoriaService();
            try{
                                                    
                categorias = cateSer.traerTodo();
                
                request.setAttribute("categorias", categorias);
                request.getRequestDispatcher("producto_nuevo.jsp").forward(request,response);
                
            }catch(Exception ex){
                request.getRequestDispatcher("error.jsp").forward(request,response);
            }
            
        }else if(accion.equals("crear")) {
         
            ProductoTO proTO = new ProductoTO();
            try{
            
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                                
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List  items = upload.parseRequest(request);
                
                // Process the uploaded items
                for(Object fileItem:items) {
                    FileItem item = (FileItem) fileItem;

                    if (item.isFormField()) {
                       if(item.getFieldName().equals("txtNombre")) {
                           proTO.setNombre(item.getString());           
                       }else if(item.getFieldName().equals("txtPrecio")) {
                           proTO.setPrecio(Float.parseFloat(item.getString()));       
                        }else if(item.getFieldName().equals("txtStock")) {
                            proTO.setStock(Integer.parseInt(item.getString()));        
                        }else if(item.getFieldName().equals("cboCategoria")) {
                            proTO.setCategoriaTO(new CategoriaTO(
                                                Integer.parseInt(item.getString()), "", null));        
                        }                       
                    } else {
                        proTO.setImagen(item.get());                    
                    }
                }
                                
                proSer.crear(proTO);
                
                response.setStatus(200);
                response.getWriter().write("Se inserto el registro");
                
            }catch(Exception ex){
                response.setStatus(500);
                response.getWriter().write(ex.getMessage());
            }
            
        } else if(accion.equals("traer_por_nombre")) {            

                ArrayList<ProductoTO> productos = null;                
                try{
                                                        
                    productos = proSer.traerPorNombre(request.getParameter("txtNombre"));
                    
                    request.getSession(true).setAttribute("productos", productos);
                    
                    request.getRequestDispatcher("xml/productos.jsp").forward(request,response);    
                    
                }catch(Exception ex){
                    EcommerceLog.error(ex);
                    response.sendRedirect("error.jsp");
                }            
        }else if(accion.equals("traer_datos_grafica1")) {            

                HashMap datos = null;                
                try{
                                                        
                    datos = proSer.traerDatosGrafica1();
                    
                    //Crear la grafica con JFreeChart
                     DefaultCategoryDataset dataset = new DefaultCategoryDataset();                                  
                    
                    Set set = datos.entrySet();
                    Iterator i = set.iterator();
                    while(i.hasNext()){
                          Map.Entry me = (Map.Entry)i.next();                        
                          dataset.addValue(Integer.parseInt(me.getValue().toString()), "Cantidad",me.getKey().toString());
                    }

                     JFreeChart chart = ChartFactory.createBarChart("Cantidad de Productos por Categoria", 
                                                     "Categoria", 
                                                     "Cantidad", 
                                                     dataset, 
                                                     PlotOrientation.VERTICAL, 
                                                     true, 
                                                     true, 
                                                     false 
                                                     );
                    
                    ChartUtilities.writeChartAsJPEG(response.getOutputStream(),chart,400,250);
                    
                }catch(Exception ex){
                    EcommerceLog.error(ex);
                    response.sendRedirect("error.jsp");
                }
            }

    }
}
